let express = require('express');
let router = express.Router();
let { lxtuserModel } = require('../model/model');
let jwt = require('jsonwebtoken');
const nodemailer = require('nodemailer');
const randomstring = require('randomstring');
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const axios = require('axios');
const crypto = require("crypto");

// 获取真实的公网IP地址
async function getRealPublicIp() {
  try {
    console.log('🌐 获取真实公网IP地址...');
    
    // 尝试多个IP查询服务
    const ipServices = [
      'https://api.ipify.org?format=json',
      'https://ipinfo.io/json',
      'https://httpbin.org/ip',
      'https://ipapi.co/json'
    ];

    for (const service of ipServices) {
      try {
        const response = await axios.get(service, {
          timeout: 3000,
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
          }
        });

        let ip = '';
        if (service.includes('ipify')) {
          ip = response.data.ip;
        } else if (service.includes('ipinfo')) {
          ip = response.data.ip;
        } else if (service.includes('httpbin')) {
          ip = response.data.origin;
        } else if (service.includes('ipapi')) {
          ip = response.data.ip;
        }

        if (ip && !ip.startsWith('127.') && !ip.startsWith('192.168.') && !ip.startsWith('10.') && ip !== '::1') {
          console.log('✅ 成功获取公网IP:', ip, '(来源:', service, ')');
          return ip;
        }
      } catch (err) {
        console.log('⚠️ IP服务失败:', service, err.message);
        continue;
      }
    }

    throw new Error('所有IP查询服务都失败了');
  } catch (error) {
    console.error('❌ 获取公网IP失败:', error.message);
    // 如果无法获取公网IP，返回一个标识
    return 'UNKNOWN_PUBLIC_IP';
  }
}

// IP地理位置查询服务 (强制使用网络IP)
async function getIpGeolocation(requestIp) {
  try {
    let targetIp = requestIp;

    // 如果是本地IP，强制获取真实公网IP
    if (requestIp === '127.0.0.1' || requestIp === '::1' || 
        requestIp.startsWith('192.168.') || requestIp.startsWith('10.') || 
        requestIp.startsWith('172.') || requestIp === 'UNKNOWN_PUBLIC_IP') {
      
      console.log('🔄 检测到本地IP，获取真实公网IP...');
      targetIp = await getRealPublicIp();
      
      if (targetIp === 'UNKNOWN_PUBLIC_IP') {
        console.log('⚠️ 无法获取公网IP，使用默认位置信息');
        return {
          ip: 'UNKNOWN_PUBLIC_IP',
          originalIp: requestIp,
          country: 'China',
          region: 'Unknown',
          city: 'Unknown',
          latitude: 39.9042,
          longitude: 116.4074,
          isp: 'Unknown ISP',
          timezone: 'Asia/Shanghai',
          isPublicIp: false
        };
      }
    }

    console.log('🌍 查询IP地理位置:', targetIp);
    const response = await axios.get(`https://ipapi.co/${targetIp}/json/`, {
      timeout: 5000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
      }
    });

    const data = response.data;
    const location = {
      ip: targetIp,
      originalIp: requestIp !== targetIp ? requestIp : undefined,
      country: data.country_name || 'Unknown',
      region: data.region || 'Unknown',
      city: data.city || 'Unknown',
      latitude: parseFloat(data.latitude) || 0,
      longitude: parseFloat(data.longitude) || 0,
      isp: data.org || 'Unknown',
      timezone: data.timezone || 'UTC',
      isPublicIp: true
    };

    console.log('✅ IP地理位置查询成功:', location);
    return location;

  } catch (error) {
    console.error('❌ IP地理位置查询失败:', error.message);
    // 返回默认位置信息
    return {
      ip: requestIp,
      country: 'Unknown',
      region: 'Unknown',
      city: 'Unknown',
      latitude: 0,
      longitude: 0,
      isp: 'Unknown',
      timezone: 'UTC',
      isPublicIp: false
    };
  }
}

// 计算两个地理位置之间的距离（单位：公里）
function calculateDistance(lat1, lon1, lat2, lon2) {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
            Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  return R * c;
}

// 分析是否为常用登录地点
function analyzeLoginLocation(currentLocation, loginHistory) {
  if (!loginHistory || loginHistory.length === 0) {
    console.log('🆕 首次登录，无历史记录');
    return { isCommonLocation: true, reason: '首次登录' };
  }

  // 获取最近5次登录记录
  const recentLogins = loginHistory.slice(-5);
  console.log('📊 分析最近登录记录数量:', recentLogins.length);

  let commonLocationCount = 0;
  let minDistance = Infinity;
  let avgDistance = 0;
  let totalDistance = 0;

  for (const login of recentLogins) {
    if (login.location && login.location.latitude && login.location.longitude) {
      const distance = calculateDistance(
        currentLocation.latitude,
        currentLocation.longitude,
        login.location.latitude,
        login.location.longitude
      );

      totalDistance += distance;
      minDistance = Math.min(minDistance, distance);

      console.log(`📍 与历史登录点距离: ${distance.toFixed(2)}km (${login.location.city})`);

      // 50公里内视为同一地点
      if (distance <= 50) {
        commonLocationCount++;
      }
    }
  }

  avgDistance = totalDistance / recentLogins.length;

  // 判断规则
  const isCommonLocation = commonLocationCount >= Math.ceil(recentLogins.length * 0.4) || minDistance <= 20;
  
  const analysis = {
    isCommonLocation,
    minDistance: minDistance === Infinity ? 0 : minDistance,
    avgDistance: avgDistance || 0,
    commonLocationCount,
    totalHistory: recentLogins.length,
    reason: isCommonLocation ? 
      `常用地点 (${commonLocationCount}/${recentLogins.length}次在附近, 最近距离${minDistance.toFixed(1)}km)` :
      `异地登录 (最近距离${minDistance.toFixed(1)}km, 平均距离${avgDistance.toFixed(1)}km)`
  };

  console.log('🔍 地点分析结果:', analysis);
  console.log('📋 详细分析信息:', {
    '当前位置': `${currentLocation.city}, ${currentLocation.region}`,
    '历史记录数': recentLogins.length,
    '最近距离': minDistance === Infinity ? '无历史记录' : `${minDistance.toFixed(1)}km`,
    '平均距离': avgDistance.toFixed(1) + 'km',
    '附近登录次数': `${commonLocationCount}/${recentLogins.length}`,
    '判断标准': minDistance <= 20 ? '距离≤20km' : `附近登录比例≥${Math.ceil(recentLogins.length * 0.4)}次`,
    '最终结果': analysis.isCommonLocation ? '常用地点(LOW)' : '异地登录(HIGH)'
  });
  return analysis;
}

// 从请求中获取真实IP地址
function getRealIp(req) {
  let ip = req.headers['x-forwarded-for'] || 
           req.headers['x-real-ip'] || 
           req.connection.remoteAddress || 
           req.socket.remoteAddress ||
           (req.connection.socket ? req.connection.socket.remoteAddress : null) ||
           req.ip ||
           '127.0.0.1';
  
  // 处理IPv6本地回环地址
  if (ip === '::1') {
    ip = '127.0.0.1'; // 统一转换为IPv4格式
  }
  
  // 处理x-forwarded-for多个IP的情况（代理链）
  if (ip && ip.includes(',')) {
    ip = ip.split(',')[0].trim(); // 取第一个IP（真实客户端IP）
  }
  
  // 移除IPv6映射前缀
  if (ip && ip.startsWith('::ffff:')) {
    ip = ip.substring(7);
  }
  
      console.log('🔍 原始IP信息:', {
      'x-forwarded-for': req.headers['x-forwarded-for'],
      'x-real-ip': req.headers['x-real-ip'],
      'connection.remoteAddress': req.connection.remoteAddress,
      'socket.remoteAddress': req.socket.remoteAddress,
      'req.ip': req.ip,
      '最终IP': ip,
      '注意': '如果是本地IP将自动获取真实公网IP'
    });
  
  return ip;
}

// 记录用户登录IP和时间（升级版，包含地理位置）
async function recordLoginInfo(user, clientIp, userAgent, loginMethod = 'password', isSecureLogin = false) {
  try {
    console.log('📝 记录登录信息:', {
      userId: user._id,
      username: user.username,
      ip: clientIp,
      userAgent: userAgent,
      loginMethod: loginMethod,
      isSecureLogin: isSecureLogin
    });

    // 获取IP地理位置信息
    const location = await getIpGeolocation(clientIp);

    // 更新用户的登录时间和IP（这些字段在当前模型中已存在）
    user.loginTime = new Date();
    user.loginip = clientIp;
    
    // 初始化必要的字段
    if (!user.loginHistory) {
      user.loginHistory = [];
    }
    if (!user.securitySettings) {
      user.securitySettings = {
        enableLocationCheck: true,
        trustedLocations: [],
        lastSecurityVerification: null
      };
    }

    // 分析登录地点风险
    const locationAnalysis = analyzeLoginLocation(location, user.loginHistory);
    
    const loginRecord = {
      ip: clientIp,
      location: location,
      timestamp: new Date(),
      userAgent: userAgent,
      loginMethod: loginMethod,
      isSecureLogin: isSecureLogin,
      riskLevel: locationAnalysis.isCommonLocation ? 'low' : 'high'
    };
    
    user.loginHistory.push(loginRecord);
    
    // 只保留最近15次登录记录
    if (user.loginHistory.length > 15) {
      user.loginHistory = user.loginHistory.slice(-15);
    }
    
    // 如果是安全验证后的登录，更新验证时间
    if (isSecureLogin) {
      user.securitySettings.lastSecurityVerification = new Date();
    }
    
    await user.save();
    console.log('✅ 登录信息记录成功 - IP:', location.ip, 
      location.originalIp ? `(原始: ${location.originalIp})` : '', 
      '地点:', `${location.city}, ${location.region}`, 
      '公网IP:', location.isPublicIp ? '是' : '否',
      '风险等级:', loginRecord.riskLevel);
    
    return { location, locationAnalysis };
    
  } catch (error) {
    console.error('❌ 记录登录信息失败:', error.message);
    // 返回默认值，避免影响登录流程
    return { 
      location: { city: 'Unknown', region: 'Unknown' },
      locationAnalysis: { isCommonLocation: true, reason: '记录失败，允许登录' }
    };
  }
}

// 水滴聚合配置
const SHUIDI_CONFIG = {
  baseUrl: 'http://uniqueker.top',  // 修正协议，与平台配置保持一致
  appid: '3749',
  appkey: '247aa1bcb8878e75fd72973b07fd80c9',
  callbackDomain: '13be2816e0e8.ngrok-free.app'
};

// JWT密钥
const JWT_SECRET = "123";

// 推送助手配置
const PUSH_CONFIG = {
  url: 'https://push.spug.cc/send/XlxGd8JwyWm2bn0R'
};

// 存储验证码 (实际生产环境应使用Redis或数据库)
const resetCodes = new Map();

// 临时令牌存储（用于二次验证流程）
const tempTokens = new Map();

// 生成临时令牌（用于二次验证）
function generateTempToken(userId, purpose) {
  const token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  const tokenData = {
    userId: userId,
    purpose: purpose,
    createdAt: new Date(),
    expiresAt: new Date(Date.now() + 15 * 60 * 1000) // 15分钟过期
  };
  
  tempTokens.set(token, tokenData);
  
  // 清理过期令牌
  setTimeout(() => {
    tempTokens.delete(token);
  }, 15 * 60 * 1000);
  
  return token;
}

// 获取可用的验证方式
function getAvailableVerificationMethods(user) {
  const methods = [];
  
  if (user.phone) {
    methods.push({
      type: 'phone',
      label: '手机验证码',
      target: `${user.phone.substring(0, 3)}****${user.phone.substring(7)}`
    });
  }
  
  if (user.email) {
    methods.push({
      type: 'email',
      label: '邮箱验证码',
      target: `${user.email.substring(0, 3)}****@${user.email.split('@')[1]}`
    });
  }
  
  // 密码验证始终可用
  methods.push({
    type: 'password',
    label: '密码验证',
    target: '输入当前密码'
  });
  
  return methods;
}

// 创建邮件发送器
const transporter = nodemailer.createTransport({
  service: 'qq', // 可以是 'Gmail', 'QQ', '163' 等
  auth: {
    user: '809151340@qq.com', // 您的邮箱
    pass: 'hwocnumukxmfbahj' // 您的邮箱授权码
  }
});

// 生成验证码
function generateVerificationCode() {
  return randomstring.generate({
    length: 6,
    charset: 'numeric'
  });
}

// 发送邮件
async function sendEmail(to, code) {
  const mailOptions = {
    from: '809151340@qq.com', // 发件人
    to: to, // 收件人
    subject: '账号注册验证码', // 主题
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;">
        <h2 style="color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px;">注册验证码</h2>
        <p>您好，</p>
        <p>您正在进行账号注册操作，您的验证码是：</p>
        <div style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; font-size: 24px; font-weight: bold; text-align: center; letter-spacing: 5px;">
          ${code}
        </div>
        <p>此验证码10分钟内有效，请勿泄露给他人。</p>
        <p>如果您没有请求此验证码，请忽略此邮件。</p>
        <p style="margin-top: 20px; color: #777; font-size: 12px;">此邮件为系统自动发送，请勿回复。</p>
      </div>
    `
  };

  try {
    // 开发环境下也打印验证码到控制台
    console.log(`邮件验证码 (${to}): ${code}`);
    
    // 发送邮件
    const result = await transporter.sendMail(mailOptions);
    console.log('邮件发送成功:', result);
    return result;
  } catch (error) {
    console.error('邮件发送失败:', error);
    throw error;
  }
}

// 发送推送助手短信验证码
async function sendSMS(phoneNumber, code) {
  try {
    console.log(`发送推送助手短信到 ${phoneNumber}, 验证码: ${code}`);
    
    // 推送助手的请求数据
    const requestData = {
      name: '推送助手',
      code: code,
      targets: phoneNumber
    };
    
    console.log('推送助手请求数据:', requestData);
    
    // 发送请求到推送助手
    const response = await axios.post(PUSH_CONFIG.url, requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('推送助手响应:', response.data);
    
    if (response.data && response.data.code === 200) {
      console.log(`短信验证码发送成功到 ${phoneNumber}`);
      return Promise.resolve();
    } else {
      console.error('推送助手发送失败:', response.data);
      throw new Error(response.data.msg || '短信发送失败');
    }
    
  } catch (error) {
    console.error('发送短信验证码失败:', error);
    throw error;
  }
}

/* 登录 */
router.post("/login", async function (req, res, next) {
    try {
        let { phone, email, username, password, loginType, verificationCode } = req.body;
        console.log('登录请求数据:', req.body);
        
        // 获取客户端真实IP和用户代理
        const clientIp = getRealIp(req);
        const userAgent = req.headers['user-agent'] || '';
        console.log('🌐 登录IP地址:', clientIp, '用户代理:', userAgent);
        
        // 验证码登录
        if (loginType === 'code') {
            if (!phone && !email) {
                return res.status(400).send({
                    code: 400,
                    msg: "请提供手机号或邮箱"
                });
            }
            
            if (!verificationCode) {
                return res.status(400).send({
                    code: 400,
                    msg: "请提供验证码"
                });
            }
            
            // 确定目标（手机号或邮箱）
            const target = phone || email;
            console.log('验证码登录验证:', { target, verificationCode, phone, email });
            
            // 验证验证码
            const storedCodeData = resetCodes.get(target);
            console.log('存储的验证码数据:', storedCodeData);
            
            if (!storedCodeData) {
                return res.status(400).send({
                    code: 400,
                    msg: "验证码不存在或已过期，请重新获取"
                });
            }
            
            if (new Date() > storedCodeData.expiresAt) {
                resetCodes.delete(target);
                return res.status(400).send({
                    code: 400,
                    msg: "验证码已过期，请重新获取"
                });
            }
            
            if (verificationCode !== storedCodeData.code) {
                return res.status(400).send({
                    code: 400,
                    msg: "验证码不正确"
                });
            }
            
            // 验证通过后删除验证码
            resetCodes.delete(target);
            
            // 查找用户
            let findUser;
            if (phone) {
                findUser = await lxtuserModel.findOne({ phone });
            } else {
                findUser = await lxtuserModel.findOne({ email });
            }
            
            if (!findUser) {
                return res.status(400).send({
                    code: 400,
                    msg: `${phone ? '手机号' : '邮箱'}未注册，请先注册`
                });
            }
            
            // 记录登录IP信息并进行地点分析
            const { location, locationAnalysis } = await recordLoginInfo(findUser, clientIp, userAgent, 'code');
            
            // 检查是否为风险用户或需要二次验证
            const isRiskUser = findUser.securitySettings?.isRiskUser || false;
            const needsSecurityVerification = isRiskUser || (!locationAnalysis.isCommonLocation && findUser.securitySettings?.enableLocationCheck);
            
            console.log('🔍 验证码登录安全检查:', {
                '用户手机': findUser.phone,
                '是否风险用户': isRiskUser,
                '风险原因': findUser.securitySettings?.riskUserReason,
                '是否常用地点': locationAnalysis.isCommonLocation,
                '启用地点检测': findUser.securitySettings?.enableLocationCheck,
                '需要二次验证': needsSecurityVerification
            });
            
            if (needsSecurityVerification) {
                const reason = isRiskUser ? '风险用户强制验证' : '检测到异地登录';
                const reasonMsg = isRiskUser ? '您的账户已被标记为风险用户，需要进行安全验证' : '检测到异地登录，需要进行安全验证';
                console.log(`🚨 ${reason}，需要二次验证`);
                
                // 返回需要二次验证的响应
                return res.status(202).send({
                    code: 202,
                    msg: reasonMsg,
                    requiresSecurityVerification: true,
                    isRiskUser: isRiskUser,
                    riskReason: isRiskUser ? findUser.securitySettings?.riskUserReason : undefined,
                    location: {
                        current: `${location.city}, ${location.region}`,
                        country: location.country
                    },
                    analysis: locationAnalysis,
                    verificationMethods: getAvailableVerificationMethods(findUser),
                    tempToken: generateTempToken(findUser._id, isRiskUser ? 'risk_user_verification' : 'location_verification')
                });
            }
            
            // 登录成功，生成token
            let token = "Bearer " + jwt.sign({ 
                phone: findUser.phone, 
                userId: findUser._id,
                username: findUser.username
            }, JWT_SECRET, {
                expiresIn: "24h"
            });
            
            res.send({
                code: 200,
                msg: "登录成功",
                token,
                user: {
                    id: findUser._id,
                    phone: findUser.phone,
                    email: findUser.email,
                    username: findUser.username,
                    shenfen: findUser.shenfen
                }
            });
            return;
        }
        
        // 密码登录
        // 构建查询条件
        let queryCondition = {};
        if (phone) {
            queryCondition.phone = phone;
        } else if (email) {
            queryCondition.email = email;
        } else if (username) {
            queryCondition.username = username;
        } else {
            return res.status(400).send({
                code: 400,
                msg: "请提供手机号、邮箱或用户名"
            });
        }
        
        // 添加密码到查询条件
        queryCondition.password = password;
        
        console.log('查询条件:', queryCondition);
        let findUser = await lxtuserModel.findOne(queryCondition);
        console.log('查询结果:', findUser);
        
        if (findUser) {
            // 记录登录IP信息并进行地点分析
            const { location, locationAnalysis } = await recordLoginInfo(findUser, clientIp, userAgent, 'password');
            
            // 检查是否为风险用户或需要二次验证
            const isRiskUser = findUser.securitySettings?.isRiskUser || false;
            const needsSecurityVerification = isRiskUser || (!locationAnalysis.isCommonLocation && findUser.securitySettings?.enableLocationCheck);
            
            console.log('🔍 密码登录安全检查:', {
                '用户手机': findUser.phone,
                '是否风险用户': isRiskUser,
                '风险原因': findUser.securitySettings?.riskUserReason,
                '是否常用地点': locationAnalysis.isCommonLocation,
                '启用地点检测': findUser.securitySettings?.enableLocationCheck,
                '需要二次验证': needsSecurityVerification
            });
            
            if (needsSecurityVerification) {
                const reason = isRiskUser ? '风险用户强制验证' : '检测到异地登录';
                const reasonMsg = isRiskUser ? '您的账户已被标记为风险用户，需要进行安全验证' : '检测到异地登录，需要进行安全验证';
                console.log(`🚨 ${reason}，需要二次验证`);
                
                // 返回需要二次验证的响应
                return res.status(202).send({
                    code: 202,
                    msg: reasonMsg,
                    requiresSecurityVerification: true,
                    isRiskUser: isRiskUser,
                    riskReason: isRiskUser ? findUser.securitySettings?.riskUserReason : undefined,
                    location: {
                        current: `${location.city}, ${location.region}`,
                        country: location.country
                    },
                    analysis: locationAnalysis,
                    verificationMethods: getAvailableVerificationMethods(findUser),
                    tempToken: generateTempToken(findUser._id, isRiskUser ? 'risk_user_verification' : 'location_verification')
                });
            }
            
            // 登录成功，生成token
            let token = "Bearer " + jwt.sign({ 
                phone: findUser.phone, 
                userId: findUser._id,
                username: findUser.username
            }, JWT_SECRET, {
                expiresIn: "24h"
            });
            
            res.send({
                code: 200,
                msg: "登录成功",
                token,
                user: {
                    id: findUser._id,
                    phone: findUser.phone,
                    email: findUser.email,
                    username: findUser.username,
                    shenfen: findUser.shenfen
                }
            });
        } else {
            res.status(401).send({
                code: 401,
                msg: "用户名或密码错误"
            });
        }
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).send({
            code: 500,
            msg: "服务器错误",
            error: error.message
        });
    }
})


  //注册
  router.post("/register", async function (req, res, next) {
    try {
      let { username, shenfen, phone, email, password, verificationCode, type } = req.body;
      console.log('注册请求数据:', req.body);
      console.log('解析的字段:', { username, shenfen, phone, email, password, verificationCode, type });
      
      // 验证必填字段
      if (!username || !password) {
        console.log('验证失败: 用户名或密码为空', { username: !!username, password: !!password });
        return res.status(400).send({
          code: 400,
          msg: "用户名和密码不能为空"
        });
      }
      
      // 验证手机号或邮箱
      if (type === 'phone' && !phone) {
        return res.status(400).send({
          code: 400,
          msg: "手机号不能为空"
        });
      }
      
      if (type === 'email' && !email) {
        return res.status(400).send({
          code: 400,
          msg: "邮箱不能为空"
        });
      }
      
      // 验证验证码
      if (verificationCode) {
        const target = type === 'phone' ? phone : email;
        console.log('验证码验证:', { target, verificationCode, type });
        const storedCodeData = resetCodes.get(target);
        console.log('存储的验证码数据:', storedCodeData);
        
        if (!storedCodeData) {
          console.log('验证码不存在');
          return res.status(400).send({
            code: 400,
            msg: "验证码不存在或已过期，请重新获取"
          });
        }
        
        if (new Date() > storedCodeData.expiresAt) {
          resetCodes.delete(target);
          return res.status(400).send({
            code: 400,
            msg: "验证码已过期，请重新获取"
          });
        }
        
        if (verificationCode !== storedCodeData.code) {
          return res.status(400).send({
            code: 400,
            msg: "验证码不正确"
          });
        }
        
        // 验证通过后删除验证码
        resetCodes.delete(target);
      }
      
      // 检查用户是否已存在
      let existingUser = null;
      if (phone) {
        existingUser = await lxtuserModel.findOne({ phone });
      } else if (email) {
        existingUser = await lxtuserModel.findOne({ email });
      }
      
      if (existingUser) {
        return res.status(400).send({
          code: 400,
          msg: `${type === 'phone' ? '手机号' : '邮箱'}已被注册`
        });
      }
      
      // 创建用户
      const userData = {
        username,
        shenfen: shenfen || 'user',
        password,
        loginType: 'normal',     // 普通注册设置为normal
        createTime: new Date(),
        updateTime: new Date()
      };
      
      if (phone) userData.phone = phone;
      if (email) userData.email = email;
      
      const newUser = await lxtuserModel.create(userData);
      
      console.log('用户创建成功:', newUser);
      
      res.send({
        code: 200,
        msg: "注册成功",
        success: true,
        user: {
          id: newUser._id,
          username: newUser.username,
          phone: newUser.phone,
          email: newUser.email,
          shenfen: newUser.shenfen
        }
      });
      
    } catch (error) {
      console.error('注册错误:', error);
      res.status(500).send({
        code: 500,
        msg: "注册失败，请稍后重试",
        error: error.message
      });
    }
  })

// 验证Token的路由
router.get('/verify-token', (req, res) => {
  // 从请求头中获取token
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return res.status(401).json({
      code: 401,
      msg: '没有提供token',
      isValid: false
    });
  }

  // 验证Bearer格式
  const parts = authHeader.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    return res.status(401).json({
      code: 401,
      msg: 'token格式错误，正确格式为: Bearer [token]',
      isValid: false
    });
  }

  const token = parts[1];

  // 验证token
  try {
    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    
    // 返回验证成功信息
    res.json({
      code: 200,
      msg: 'token有效',
      isValid: true,
      user: decoded
    });
  } catch (err) {
    // token无效或过期
    res.status(401).json({
      code: 401,
      msg: 'token无效或已过期',
      isValid: false,
      error: err.message
    });
  }
});

// JWT验证中间件
const verifyJWT = (req, res, next) => {
  // 从请求头中获取token
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return res.status(401).json({
      code: 401,
      msg: '没有提供token'
    });
  }

  // 验证Bearer格式
  const parts = authHeader.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    return res.status(401).json({
      code: 401,
      msg: 'token格式错误，正确格式为: Bearer [token]'
    });
  }

  const token = parts[1];

  // 验证token
  try {
    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    
    // 将解码后的用户信息添加到请求对象中
    req.user = decoded;
    
    // 继续下一步
    next();
  } catch (err) {
    // token无效或过期
    res.status(401).json({
      code: 401,
      msg: 'token无效或已过期',
      error: err.message
    });
  }
};

// 受保护的路由示例 - 获取用户信息
router.get('/user-info', verifyJWT, async (req, res) => {
  try {
    // 从req.user中获取用户ID
    const { phone } = req.user;
    
    // 查询数据库获取完整用户信息
    const user = await lxtuserModel.findOne({ phone }).select('-password');
    
    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: '未找到用户信息'
      });
    }
    
    // 返回用户信息
    res.json({
      code: 200,
      msg: '获取用户信息成功',
      user
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误',
      error: error.message
    });
  }
});

// 发送重置密码验证码
router.post('/send-reset-code', [
  body('phone').optional().isMobilePhone('zh-CN').withMessage('请提供有效的手机号码'),
  body('email').optional().isEmail().withMessage('请提供有效的邮箱地址')
], async (req, res) => {
  try {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        msg: errors.array()[0].msg
      });
    }

    const { phone, email } = req.body;

    // 确保提供了手机号或邮箱
    if (!phone && !email) {
      return res.status(400).json({
        code: 400,
        msg: '请提供手机号或邮箱'
      });
    }

    // 查找用户
    const findCondition = phone ? { phone } : { email };
    const user = await lxtuserModel.findOne(findCondition);

    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: `未找到与该${phone ? '手机号' : '邮箱'}关联的账户`
      });
    }

    // 生成验证码
    const verificationCode = generateVerificationCode();
    
    // 存储验证码，设置10分钟有效期
    const codeData = {
      code: verificationCode,
      userId: user._id,
      expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10分钟后过期
    };

    const contactKey = phone || email;
    resetCodes.set(contactKey, codeData);
    
    console.log('验证码已存储:', {
      contactKey,
      code: verificationCode,
      expiresAt: codeData.expiresAt,
      totalCodes: resetCodes.size
    });

    // 发送验证码
    if (phone) {
      await sendSMS(phone, verificationCode);
    } else if (email) {
      await sendEmail(email, verificationCode);
    }

    // 返回成功信息
    res.json({
      code: 200,
      msg: `验证码已发送到您的${phone ? '手机' : '邮箱'}`
    });

  } catch (error) {
    console.error('发送重置码错误:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 验证重置密码验证码
router.post('/verify-reset-code', [
  body('phone').optional().isMobilePhone('zh-CN').withMessage('请提供有效的手机号码'),
  body('email').optional().isEmail().withMessage('请提供有效的邮箱地址'),
  body('code').isLength({ min: 6, max: 6 }).withMessage('验证码应为6位')
], async (req, res) => {
  try {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        msg: errors.array()[0].msg
      });
    }

    const { phone, email, code } = req.body;

    // 确保提供了手机号或邮箱
    if (!phone && !email) {
      return res.status(400).json({
        code: 400,
        msg: '请提供手机号或邮箱'
      });
    }

    const contactKey = phone || email;
    const storedCodeData = resetCodes.get(contactKey);

    // 验证码不存在
    if (!storedCodeData) {
      return res.status(400).json({
        code: 400,
        msg: '验证码不存在或已过期，请重新获取'
      });
    }

    // 验证码已过期
    if (new Date() > storedCodeData.expiresAt) {
      resetCodes.delete(contactKey); // 删除过期验证码
      return res.status(400).json({
        code: 400,
        msg: '验证码已过期，请重新获取'
      });
    }

    // 验证码不匹配
    if (code !== storedCodeData.code) {
      return res.status(400).json({
        code: 400,
        msg: '验证码不正确'
      });
    }

    // 验证通过，延长验证码有效期（给用户充足时间设置新密码）
    storedCodeData.expiresAt = new Date(Date.now() + 30 * 60 * 1000); // 30分钟
    resetCodes.set(contactKey, storedCodeData);

    res.json({
      code: 200,
      msg: '验证码验证成功'
    });

  } catch (error) {
    console.error('验证重置码错误:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 重置密码
router.post('/reset-password', [
  body('phone').optional().isMobilePhone('zh-CN').withMessage('请提供有效的手机号码'),
  body('email').optional().isEmail().withMessage('请提供有效的邮箱地址'),
  body('code').isLength({ min: 6, max: 6 }).withMessage('验证码应为6位'),
  body('newPassword')
    .isLength({ min: 8, max: 16 }).withMessage('密码长度应在8-16位之间')
    .matches(/^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,16}$/)
    .withMessage('密码需包含大写字母、小写字母、数字和特殊符号')
    .not().matches(/(.)\1\1/) // 不能有连续重复3个及以上的字符
    .withMessage('密码不能包含重复的三个及以上字符')
    .not().matches(/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789|890)/i)
    .withMessage('密码不能包含连续的三个及以上字符或数字')
], async (req, res) => {
  try {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        msg: errors.array()[0].msg
      });
    }

    const { phone, email, code, newPassword } = req.body;

    // 确保提供了手机号或邮箱
    if (!phone && !email) {
      return res.status(400).json({
        code: 400,
        msg: '请提供手机号或邮箱'
      });
    }

    const contactKey = phone || email;
    const storedCodeData = resetCodes.get(contactKey);

    // 验证码不存在
    if (!storedCodeData) {
      return res.status(400).json({
        code: 400,
        msg: '验证码不存在或已过期，请重新获取'
      });
    }

    // 验证码已过期
    if (new Date() > storedCodeData.expiresAt) {
      resetCodes.delete(contactKey); // 删除过期验证码
      return res.status(400).json({
        code: 400,
        msg: '验证码已过期，请重新获取'
      });
    }

    // 验证码不匹配
    if (code !== storedCodeData.code) {
      return res.status(400).json({
        code: 400,
        msg: '验证码不正确'
      });
    }

    // 直接存储明文密码
    const findCondition = phone ? { phone } : { email };
    const updateResult = await lxtuserModel.updateOne(findCondition, {
      password: newPassword,
      updateTime: new Date()
    });

    if (updateResult.modifiedCount === 0) {
      return res.status(500).json({
        code: 500,
        msg: '密码更新失败'
      });
    }

    // 删除已使用的验证码
    resetCodes.delete(contactKey);

    res.json({
      code: 200,
      msg: '密码重置成功'
    });

  } catch (error) {
    console.error('重置密码错误:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 发送验证码路由
router.post('/send-verification-code', async (req, res) => {
  try {
    const { type, target, purpose } = req.body;
    
    console.log('发送验证码请求:', { type, target, purpose });
    
    if (!type || !target) {
      return res.status(400).json({
        code: 400,
        msg: '请提供发送类型和目标'
      });
    }
    
    // 生成验证码
    const verificationCode = generateVerificationCode();
    
    // 存储验证码，设置10分钟有效期
    const codeData = {
      code: verificationCode,
      target: target,
      type: type,
      purpose: purpose || 'login',
      expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10分钟后过期
    };
    
    resetCodes.set(target, codeData);
    console.log('验证码已存储:', { target, code: verificationCode, purpose });
    
    // 根据类型发送验证码
    if (type === 'email') {
      await sendEmail(target, verificationCode);
    } else if (type === 'phone') {
      await sendSMS(target, verificationCode);
    } else {
      return res.status(400).json({
        code: 400,
        msg: '不支持的验证码类型'
      });
    }
    
    res.json({
      code: 200,
      msg: `验证码已发送到您的${type === 'email' ? '邮箱' : '手机'}`,
      success: true
    });
    
  } catch (error) {
    console.error('发送验证码失败:', error);
    res.status(500).json({
      code: 500,
      msg: '验证码发送失败，请稍后再试',
      error: error.message
    });
  }
});

// 测试邮箱发送功能的路由
router.post('/test-email', async (req, res) => {
  try {
    const { email } = req.body;
    
    if (!email) {
      return res.status(400).json({
        code: 400,
        msg: '请提供邮箱地址'
      });
    }

    // 生成测试验证码
    const testCode = generateVerificationCode();
    
    // 发送测试邮件
    await sendEmail(email, testCode);
    
    res.json({
      code: 200,
      msg: '测试邮件发送成功',
      testCode: testCode // 在开发环境下返回验证码用于测试
    });
    
  } catch (error) {
    console.error('测试邮件发送失败:', error);
    res.status(500).json({
      code: 500,
      msg: '邮件发送失败',
      error: error.message
    });
  }
});

// 测试推送助手短信发送功能的路由
router.post('/test-sms', async (req, res) => {
  try {
    const { phone } = req.body;
    
    if (!phone) {
      return res.status(400).json({
        code: 400,
        msg: '请提供手机号'
      });
    }

    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return res.status(400).json({
        code: 400,
        msg: '请输入有效的手机号'
      });
    }

    // 生成测试验证码
    const testCode = generateVerificationCode();
    
    // 发送测试短信
    await sendSMS(phone, testCode);
    
    res.json({
      code: 200,
      msg: '测试短信发送成功',
      testCode: testCode // 在开发环境下返回验证码用于测试
    });
    
  } catch (error) {
    console.error('测试短信发送失败:', error);
    res.status(500).json({
      code: 500,
      msg: '短信发送失败',
      error: error.message
    });
  }
});

// 水滴聚合第三方登录路由
router.get('/shuidi-login', async (req, res) => {
  console.log('收到水滴聚合登录请求:', req.query);
  console.log('请求URL:', req.url);
  console.log('请求方法:', req.method);
  
  try {
    let { type } = req.query; // type: 'qq', 'wx', 'wechat' 等
    
    console.log('原始登录类型:', type);
    
    // 标准化登录类型
    if (type === 'wechat' || type === 'weixin') {
      type = 'wx';
    }
    
    console.log('标准化后登录类型:', type);
    
    if (!type || !['qq', 'wx'].includes(type)) {
      console.log('无效的登录类型:', type);
      return res.status(400).json({
        code: 400,
        msg: '请指定登录类型：qq、wx 或 wechat'
      });
    }

    // 调用水滴聚合API获取登录URL（使用HTTPS避免ngrok重定向问题）
    const apiUrl = `${SHUIDI_CONFIG.baseUrl}/connect.php?act=login&appid=${SHUIDI_CONFIG.appid}&appkey=${SHUIDI_CONFIG.appkey}&type=${type}&redirect_uri=${encodeURIComponent(`https://${SHUIDI_CONFIG.callbackDomain}/lxt/shuidi-callback`)}`;
    
    console.log('调用水滴聚合API:', apiUrl);
    console.log('水滴聚合配置:', SHUIDI_CONFIG);
    
    // 调用水滴聚合API获取真实的登录URL
    const response = await axios.get(apiUrl, {
      timeout: 30000, // 增加到30秒超时
      headers: {
        'ngrok-skip-browser-warning': 'true', // 添加ngrok跳过浏览器警告的请求头
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
      },
      validateStatus: function (status) {
        return status < 500; // 接受所有小于500的状态码
      }
    });
    
    console.log('水滴聚合API响应:', response.data);
    
    if (response.data.code === 0) {
      // 成功获取登录URL
      res.json({
        code: 200,
        msg: '获取登录链接成功',
        loginUrl: response.data.url,
        qrcode: response.data.qrcode || null,
        type: response.data.type
      });
    } else {
      // API返回错误
      res.status(400).json({
        code: 400,
        msg: response.data.msg || '获取登录链接失败',
        errcode: response.data.code
      });
    }
    
  } catch (error) {
    console.error('获取水滴聚合登录链接失败:', error);
    res.status(500).json({
      code: 500,
      msg: '获取登录链接失败',
      error: error.message
    });
  }
});

// 诊断路由 - 用于调试第三方登录问题
router.get('/shuidi-debug', async (req, res) => {
  try {
    console.log('=== 第三方登录诊断 ===');
    
    const diagnostics = {
      timestamp: new Date().toISOString(),
      server: {
        status: 'running',
        port: process.env.PORT || 3001,
        environment: process.env.NODE_ENV || 'development'
      },
             shuidiConfig: {
         baseUrl: SHUIDI_CONFIG.baseUrl,
         appid: SHUIDI_CONFIG.appid,
         callbackDomain: SHUIDI_CONFIG.callbackDomain,
         callbackUrl: `https://${SHUIDI_CONFIG.callbackDomain}/lxt/shuidi-callback`
       },
      routes: {
        loginUrl: `/lxt/shuidi-login`,
        callbackUrl: `/lxt/shuidi-callback`,
                 frontendUrls: {
           loginSuccess: `https://${SHUIDI_CONFIG.callbackDomain}/login-success`,
           registerSuccess: `https://${SHUIDI_CONFIG.callbackDomain}/register-success`,
           loginError: `https://${SHUIDI_CONFIG.callbackDomain}/login-error`
         }
      },
      database: {
        status: 'connected', // 这里可以添加数据库连接检查
      },
      requestInfo: {
        userAgent: req.headers['user-agent'],
        host: req.headers.host,
        origin: req.headers.origin,
        referer: req.headers.referer
      }
    };
    
    console.log('诊断信息:', JSON.stringify(diagnostics, null, 2));
    
    res.json({
      code: 200,
      msg: '诊断完成',
      diagnostics
    });
    
  } catch (error) {
    console.error('诊断失败:', error);
    res.status(500).json({
      code: 500,
      msg: '诊断失败',
      error: error.message
    });
  }
});



// 水滴聚合回调处理
router.get('/shuidi-callback', async (req, res) => {
  try {
    console.log('=== 水滴聚合回调开始 ===');
    console.log('完整URL:', req.url);
    console.log('查询参数:', req.query);
    console.log('请求头:', req.headers);
    
    const { code, state, type } = req.query;
    
    console.log('解析的参数:', { code, state, type });
    
    if (!code) {
      console.log('错误：授权码缺失');
      // 重定向到前端错误页面，使用正确的路径
      return res.redirect(`https://${SHUIDI_CONFIG.callbackDomain}/login-error?msg=${encodeURIComponent('授权码缺失')}`);
    }

    // 获取用户信息
    const userInfoUrl = `${SHUIDI_CONFIG.baseUrl}/connect.php`;
    console.log('🔍 请求用户信息 URL:', userInfoUrl);
    console.log('🔍 请求参数:', {
      act: 'callback',
      appid: SHUIDI_CONFIG.appid,
      appkey: SHUIDI_CONFIG.appkey,
      type: type,
      code: code
    });
    
    const userInfoResponse = await axios.get(userInfoUrl, {
      params: {
        act: 'callback',
        appid: SHUIDI_CONFIG.appid,
        appkey: SHUIDI_CONFIG.appkey,
        type: type,
        code: code
      },
      timeout: 30000, // 增加到30秒超时
      headers: {
        'ngrok-skip-browser-warning': 'true', // 添加ngrok跳过浏览器警告的请求头
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
      }
    });

    console.log('🎯 水滴聚合用户信息完整响应:', JSON.stringify(userInfoResponse.data, null, 2));
    console.log('🎯 响应状态码:', userInfoResponse.status);
    console.log('🎯 响应头:', userInfoResponse.headers);

    if (userInfoResponse.data.code !== 0) {
      console.log('❌ 获取用户信息失败:', userInfoResponse.data);
      return res.redirect(`https://${SHUIDI_CONFIG.callbackDomain}/login-error?msg=${encodeURIComponent('获取用户信息失败: ' + userInfoResponse.data.msg)}`);
    }

    const userInfo = userInfoResponse.data;
    
    // 🔍 超详细用户信息打印
    console.log('🎯🎯🎯 === 扫码登录获取的用户信息 === 🎯🎯🎯');
    console.log('📱 完整用户数据对象:');
    console.log(JSON.stringify(userInfo, null, 4));
    
    console.log('📋 详细解析用户信息:');
    console.log('  ├─ 🆔 social_uid (用户唯一标识):', userInfo.social_uid);
    console.log('  ├─ 👤 nickname (昵称):', userInfo.nickname);
    console.log('  ├─ 🖼️  faceimg (头像):', userInfo.faceimg);
    console.log('  ├─ ⚧️  gender (性别):', userInfo.gender);
    console.log('  ├─ 📍 location (地址):', userInfo.location);
    console.log('  ├─ 🌐 ip (IP地址):', userInfo.ip);
    console.log('  ├─ 🔑 access_token:', userInfo.access_token);
    console.log('  ├─ 📱 phone (手机号):', userInfo.phone);
    console.log('  ├─ 📧 email (邮箱):', userInfo.email);
    console.log('  ├─ 🔐 openid:', userInfo.openid);
    console.log('  ├─ 🔐 unionid:', userInfo.unionid);
    console.log('  └─ 📊 其他字段:', Object.keys(userInfo).filter(key => 
      !['social_uid', 'nickname', 'faceimg', 'gender', 'location', 'ip', 'access_token', 'phone', 'email', 'openid', 'unionid'].includes(key)
    ).map(key => `${key}: ${userInfo[key]}`).join(', '));
    
    // 🔍 专门检查手机号信息
    if (userInfo.phone) {
      console.log('📱✅ 发现手机号信息:', userInfo.phone);
    } else {
      console.log('📱❌ 未获取到手机号信息');
      console.log('🔍 尝试查找可能的手机号字段...');
      const possiblePhoneFields = ['mobile', 'phoneNumber', 'tel', 'telephone', 'cellphone'];
      possiblePhoneFields.forEach(field => {
        if (userInfo[field]) {
          console.log(`📱🔍 在字段 "${field}" 中发现可能的手机号:`, userInfo[field]);
        }
      });
    }
    
    // 水滴聚合不直接返回手机号，我们使用social_uid作为唯一标识
    const socialUid = userInfo.social_uid;
    const nickname = userInfo.nickname;
    const faceimg = userInfo.faceimg;
    const gender = userInfo.gender;
    const location = userInfo.location;
    const access_token = userInfo.access_token;

    if (!socialUid) {
      return res.redirect(`https://${SHUIDI_CONFIG.callbackDomain}/login-error?msg=${encodeURIComponent('获取用户信息失败，缺少用户标识')}`);
    }

    // 🔍 查找用户是否存在（使用social_uid作为唯一标识）
    console.log('🔍 查找用户，使用 socialUid:', socialUid);
    let existingUser = await lxtuserModel.findOne({ socialUid: socialUid });
    console.log('🔍 数据库查询结果:', existingUser ? '找到用户' : '用户不存在');
    
    if (existingUser) {
      // 用户存在，直接登录
      console.log('✅ 用户已存在，直接登录');
      console.log('🔍 现有用户信息:', {
        id: existingUser._id,
        username: existingUser.username,
        socialUid: existingUser.socialUid,
        nickname: existingUser.nickname,
        loginType: existingUser.loginType,
        phone: existingUser.phone,
        email: existingUser.email
      });
      
      // 获取客户端真实IP和用户代理进行记录
      const clientIp = getRealIp(req);
      const userAgent = req.headers['user-agent'] || '';
      console.log('🌐 第三方登录IP:', clientIp, '用户代理:', userAgent);
      console.log('📱 水滴聚合返回的IP:', userInfo.ip);
      
      // 记录登录IP信息（第三方登录视为安全登录，不需要二次验证）
      await recordLoginInfo(existingUser, clientIp, userAgent, 'social', true);
      
      const token = "Bearer " + jwt.sign({ 
        socialUid: existingUser.socialUid, 
        userId: existingUser._id,
        username: existingUser.username
      }, JWT_SECRET, {
        expiresIn: "24h"
      });

      // 重定向到前端登录成功页面，使用正确的路径
      res.redirect(`https://${SHUIDI_CONFIG.callbackDomain}/login-success?token=${encodeURIComponent(token)}&username=${encodeURIComponent(existingUser.username)}&type=third-party`);
      
    } else {
      // 用户不存在，需要注册
      console.log('❌ 用户不存在，需要注册新用户');
      console.log('🔍 socialUid:', socialUid);
      console.log('🔍 登录类型:', type);
      
      // 生成用户名
      const username = nickname || `${type}_${socialUid.slice(-6)}`;
      console.log('🔍 生成的用户名:', username);
      
      // 🆕 准备创建新用户
      const newUserData = {
        username: username,
        socialUid: socialUid,
        nickname: nickname,
        faceimg: faceimg,
        loginType: type,
        shenfen: 'user',
        password: 'shuidi_' + Math.random().toString(36).substr(2, 9), // 随机密码
        createTime: new Date(),
        updateTime: new Date(),
        phone: userInfo.phone || null, // 如果有手机号就保存
        email: userInfo.email || null, // 如果有邮箱就保存
        gender: gender,
        location: location
      };
      
      console.log('🆕🆕🆕 创建新用户，完整数据为:');
      console.log(JSON.stringify(newUserData, null, 4));
      
      const newUser = await lxtuserModel.create(newUserData);

      console.log('✅✅✅ 新用户创建成功!');
      console.log('🔍 新用户数据库记录:', {
        id: newUser._id,
        username: newUser.username,
        socialUid: newUser.socialUid,
        nickname: newUser.nickname,
        loginType: newUser.loginType,
        phone: newUser.phone,
        email: newUser.email,
        faceimg: newUser.faceimg
      });

      // 获取客户端真实IP和用户代理进行记录
      const clientIp = getRealIp(req);
      const userAgent = req.headers['user-agent'] || '';
      console.log('🌐 新用户第三方登录IP:', clientIp, '用户代理:', userAgent);
      console.log('📱 水滴聚合返回的IP:', userInfo.ip);
      
      // 记录首次登录IP信息（新用户首次登录视为安全登录）
      await recordLoginInfo(newUser, clientIp, userAgent, 'social', true);

      const token = "Bearer " + jwt.sign({ 
        socialUid: newUser.socialUid, 
        userId: newUser._id,
        username: newUser.username
      }, JWT_SECRET, {
        expiresIn: "24h"
      });

      // 重定向到前端注册成功页面，使用正确的路径
      res.redirect(`https://${SHUIDI_CONFIG.callbackDomain}/register-success?token=${encodeURIComponent(token)}&username=${encodeURIComponent(newUser.username)}&socialUid=${socialUid}&type=third-party`);
    }
    
  } catch (error) {
    console.error('水滴聚合回调处理失败:', error);
    // 重定向到前端错误页面，使用正确的路径
    res.redirect(`https://${SHUIDI_CONFIG.callbackDomain}/login-error?msg=${encodeURIComponent('登录失败，请重试')}&error=${encodeURIComponent(error.message)}`);
  }
});




// 二次安全验证路由
router.post('/security-verification', async (req, res) => {
  try {
    const { tempToken, verificationType, verificationData } = req.body;
    
    console.log('🔐 收到二次安全验证请求:', { tempToken, verificationType });
    
    // 验证临时令牌
    const tokenData = tempTokens.get(tempToken);
    if (!tokenData || new Date() > tokenData.expiresAt) {
      return res.status(400).json({
        code: 400,
        msg: '验证令牌无效或已过期'
      });
    }
    
    // 查找用户
    const user = await lxtuserModel.findById(tokenData.userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: '用户不存在'
      });
    }
    
    let verificationPassed = false;
    
    // 根据验证类型进行验证
    switch (verificationType) {
      case 'phone':
        if (!verificationData.code) {
          return res.status(400).json({
            code: 400,
            msg: '请提供手机验证码'
          });
        }
        
        // 验证手机验证码
        const phoneCodeData = resetCodes.get(user.phone);
        if (!phoneCodeData || phoneCodeData.code !== verificationData.code || new Date() > phoneCodeData.expiresAt) {
          return res.status(400).json({
            code: 400,
            msg: '手机验证码无效或已过期'
          });
        }
        
        resetCodes.delete(user.phone);
        verificationPassed = true;
        break;
        
      case 'email':
        if (!verificationData.code) {
          return res.status(400).json({
            code: 400,
            msg: '请提供邮箱验证码'
          });
        }
        
        // 验证邮箱验证码
        const emailCodeData = resetCodes.get(user.email);
        if (!emailCodeData || emailCodeData.code !== verificationData.code || new Date() > emailCodeData.expiresAt) {
          return res.status(400).json({
            code: 400,
            msg: '邮箱验证码无效或已过期'
          });
        }
        
        resetCodes.delete(user.email);
        verificationPassed = true;
        break;
        
      case 'password':
        if (!verificationData.password) {
          return res.status(400).json({
            code: 400,
            msg: '请提供密码'
          });
        }
        
        // 验证密码
        if (user.password !== verificationData.password) {
          return res.status(400).json({
            code: 400,
            msg: '密码错误'
          });
        }
        
        verificationPassed = true;
        break;
        
      default:
        return res.status(400).json({
          code: 400,
          msg: '不支持的验证方式'
        });
    }
    
    if (verificationPassed) {
      // 清理使用过的临时令牌
      tempTokens.delete(tempToken);
      
      // 更新用户的安全验证时间和登录记录
      const clientIp = getRealIp(req);
      const userAgent = req.headers['user-agent'] || '';
      await recordLoginInfo(user, clientIp, userAgent, 'security_verified', true);
      
      // 生成正式的登录令牌
      const loginToken = "Bearer " + jwt.sign({ 
        phone: user.phone, 
        userId: user._id,
        username: user.username
      }, JWT_SECRET, {
        expiresIn: "24h"
      });
      
      console.log('✅ 二次安全验证通过，允许登录');
      
      res.json({
        code: 200,
        msg: '安全验证通过，登录成功',
        token: loginToken,
        user: {
          id: user._id,
          phone: user.phone,
          email: user.email,
          username: user.username,
          shenfen: user.shenfen
        }
      });
    }
    
  } catch (error) {
    console.error('二次安全验证失败:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 标记用户为风险用户（管理员功能）
router.post('/mark-risk-user', async (req, res) => {
  try {
    const { phone, reason, isRisk = true } = req.body;
    
    if (!phone) {
      return res.status(400).json({
        code: 400,
        msg: '请提供用户手机号'
      });
    }
    
    console.log(`🚨 ${isRisk ? '标记' : '取消标记'}风险用户:`, phone, '原因:', reason);
    
    // 查找用户
    const user = await lxtuserModel.findOne({ phone: phone });
    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: '用户不存在'
      });
    }
    
    // 初始化安全设置
    if (!user.securitySettings) {
      user.securitySettings = {
        enableLocationCheck: true,
        isRiskUser: false,
        riskUserReason: '',
        riskUserMarkedAt: null,
        trustedLocations: [],
        lastSecurityVerification: null
      };
    }
    
    // 更新风险用户状态
    user.securitySettings.isRiskUser = isRisk;
    user.securitySettings.riskUserReason = reason || (isRisk ? '管理员标记' : '');
    user.securitySettings.riskUserMarkedAt = isRisk ? new Date() : null;
    
    await user.save();
    
    console.log(`✅ 用户 ${phone} ${isRisk ? '已标记为风险用户' : '已取消风险用户标记'}`);
    
    res.json({
      code: 200,
      msg: `用户 ${phone} ${isRisk ? '已标记为风险用户' : '已取消风险用户标记'}`,
      user: {
        phone: user.phone,
        username: user.username,
        isRiskUser: user.securitySettings.isRiskUser,
        riskReason: user.securitySettings.riskUserReason,
        markedAt: user.securitySettings.riskUserMarkedAt
      }
    });
    
  } catch (error) {
    console.error('标记风险用户失败:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 查看用户风险状态
router.get('/risk-status/:phone', async (req, res) => {
  try {
    const { phone } = req.params;
    
    const user = await lxtuserModel.findOne({ phone: phone });
    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: '用户不存在'
      });
    }
    
    res.json({
      code: 200,
      data: {
        phone: user.phone,
        username: user.username,
        isRiskUser: user.securitySettings?.isRiskUser || false,
        riskReason: user.securitySettings?.riskUserReason || '',
        markedAt: user.securitySettings?.riskUserMarkedAt || null,
        enableLocationCheck: user.securitySettings?.enableLocationCheck !== false,
        lastSecurityVerification: user.securitySettings?.lastSecurityVerification || null,
        loginHistory: user.loginHistory || []
      }
    });
    
  } catch (error) {
    console.error('查询用户风险状态失败:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 发送二次验证验证码
router.post('/send-security-code', async (req, res) => {
  try {
    const { tempToken, verificationType } = req.body;
    
    console.log('📱 发送二次验证验证码:', { tempToken, verificationType });
    
    // 验证临时令牌
    const tokenData = tempTokens.get(tempToken);
    if (!tokenData || new Date() > tokenData.expiresAt) {
      return res.status(400).json({
        code: 400,
        msg: '验证令牌无效或已过期'
      });
    }
    
    // 查找用户
    const user = await lxtuserModel.findById(tokenData.userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: '用户不存在'
      });
    }
    
    // 生成验证码
    const verificationCode = generateVerificationCode();
    
    let target = '';
    let codeData = {
      code: verificationCode,
      userId: user._id,
      purpose: 'security_verification',
      expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10分钟后过期
    };
    
    if (verificationType === 'phone' && user.phone) {
      target = user.phone;
      resetCodes.set(target, codeData);
      await sendSMS(target, verificationCode);
    } else if (verificationType === 'email' && user.email) {
      target = user.email;
      resetCodes.set(target, codeData);
      await sendEmail(target, verificationCode);
    } else {
      return res.status(400).json({
        code: 400,
        msg: `该用户没有绑定${verificationType === 'phone' ? '手机号' : '邮箱'}`
      });
    }
    
    console.log(`✅ 二次验证码已发送到 ${verificationType}: ${target}`);
    
    res.json({
      code: 200,
      msg: `验证码已发送到您的${verificationType === 'phone' ? '手机' : '邮箱'}`
    });
    
  } catch (error) {
    console.error('发送二次验证码失败:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误，请稍后再试',
      error: error.message
    });
  }
});

// 导出路由和中间件
module.exports = router;
module.exports.verifyJWT = verifyJWT